package utilities;


import static com.googlecode.javacv.cpp.opencv_highgui.CV_IMWRITE_JPEG_QUALITY;
import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage;

import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.reflect.*;

import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

import servers.Dragon;
import edu.cmu.sphinx.frontend.util.Microphone;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;


public class DataSenderEngine extends Engine {

	private static boolean active = true;
	private static boolean resourceLock=false;
	public DataSenderEngine()
	{
	}
	
	public DataSenderEngine(String name, BufferedWriter log, List actionList,
			Object configData, int sleeps, EngineCommander commander) {		
		super(name, log, actionList, configData, sleeps, commander);
	}
	

	public void close() 
	{
		this.active=false;

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//recognizer.deallocate();
		
		try {
			log.write(" stopped\n");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}	
		try {
			log.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
	public void sendPicture(String targetUrl)
	{
		
		//you must do a get on the form, then a file upload with the POST command using the key of the form...
		while(resourceLock)
		{
			//wait until resource lock is  available
		}
		
		try
		{
			//get picture
			resourceLock=true;

	    	
	    	String cmd[] = {"java", "-cp", "c:\\workspace\\dragon\\bin;c:\\javalib\\javacv-bin\\javacpp.jar;c:\\javalib\\javacv-bin\\javacv.jar;c:\\javalib\\javacv-windows-x86.jar", "utilities.TakePicture"};

	    	Process p = Runtime.getRuntime().exec(cmd);

			InputStream inp = p.getInputStream();
			BufferedReader r = new BufferedReader(new InputStreamReader(inp));
			String l = null;
			while((l=r.readLine())!=null){
				System.out.println(l);
			}
			p.destroy();
			Thread.sleep(1000);
			resourceLock=false;
			//file should be created...
						

			/*
			URL yahoo = new URL(targetUrl);
	        URLConnection yc = yahoo.openConnection();
	        BufferedReader in = new BufferedReader(
	                                new InputStreamReader(
	                                yc.getInputStream()));
	        
 	        String inputLine=""; 	        
 	        StringBuffer sb=new StringBuffer();
     	    while ((inputLine = in.readLine()) != null) 
     	    {
     	    	sb.append(inputLine);
	     	}	
	        in.close();

	        
	        System.out.println(sb.toString());
	        //now get the action.....
	        String action = sb.substring(sb.indexOf("form action=")+13,sb.indexOf("\" method="));
	        
	        System.out.println(action);
	        */
			BufferedReader in;
			String inputLine;
			String action=targetUrl;
			
	        String param = "na";
	        
	        File binaryFile = new File("c:\\temp\\dragonImage.jpg");
	        String boundary = "--------------------------------------" + Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
	        String CRLF = "\r\n"; // Line separator required by multipart/form-data.

	        URLConnection connection = new URL(action).openConnection();
	        ((HttpURLConnection)connection).setRequestMethod("POST");
            ((HttpURLConnection)connection).setConnectTimeout(6000000);
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"); // Do as if you're using Firefox 3.6.3.
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            connection.setRequestProperty("accept-encoding", "gzip,deflate");
            connection.setRequestProperty("connection", "keep-alive");
            connection.setRequestProperty("accept-charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            connection.setRequestProperty("accept-language", "en-us,en;q=0.5");


	        PrintWriter writer = null;
	        try {
	            OutputStream output = connection.getOutputStream();
	            writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); // true = autoFlush, important!

	            // Send normal param.
	            writer.append(CRLF);
	            writer.append(CRLF);
	            writer.append("--" + boundary).append(CRLF);
	            writer.append("Content-Disposition: form-data; name=\"foo\"").append(CRLF);
	            writer.append("Content-Type: text/plain; charset=" + "UTF-8").append(CRLF);
	            writer.append(CRLF);
	            writer.append(param).append(CRLF).flush();
	            
	            // Send binary file.
	            writer.append("--" + boundary).append(CRLF);
	            writer.append("Content-Disposition: form-data; name=\"myFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
	            writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()));
	            writer.append(CRLF);
	            writer.append("Content-Transfer-Encoding: binary").append(CRLF);
	            writer.append(CRLF).flush();
	            InputStream input = null;
	            try {
	                input = new FileInputStream(binaryFile);
	                byte[] buffer = new byte[1024];
	                for (int length = 0; (length = input.read(buffer)) > 0;) {
	                    output.write(buffer, 0, length);
	                }
	                output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
	            } finally {
	                if (input != null) try { input.close(); } catch (IOException logOrIgnore) 
	                {
	                	logOrIgnore.printStackTrace();
	                }
	            }
	            writer.append(CRLF).flush(); // CRLF is important! It indicates end of binary boundary.

	            // End of multipart/form-data.
	            writer.append("--" + boundary + "--").append(CRLF);
	            writer.flush();
	            writer.close();
	            
	            in = new BufferedReader(
	                    new InputStreamReader(
	                    		connection.getInputStream()));
				inputLine="";
				if ((inputLine = in.readLine()) != null) 
				{
					//System.out.println(inputLine);
					log.write("Server response = " + inputLine + "\n");
				}
				in.close();
				Dragon.logToServer("Image sent");				

	        } finally {
	            if (writer != null) writer.close();
	        }
	        			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		
		
	}
	
	public void send(String action, String data)
	{
		//post this data to app controller at appDir
		try {
			StringBuffer sb = new StringBuffer();			
			URL url = new URL(this.getCommander().getAppEngineDir());			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(false);
			conn.setRequestMethod("POST");
			conn.connect();			
			sb.append("action=");
			sb.append(action);
			sb.append("&");
			sb.append("data=");
			sb.append(data);						
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());			
			writer.write(sb.toString());			
			writer.flush();						

	        BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    conn.getInputStream()));
			String inputLine="";
			if ((inputLine = in.readLine()) != null) 
			{
				System.out.println(inputLine);
				log.write("Server response = " + inputLine + "\n");
			}
			in.close();
	        writer.close();	        
	        conn.disconnect();
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
						
	}		
}
